<template>
  <div class="container">
    <div class="card">
      <h1>🧠 记忆翻牌游戏</h1>
      
      <div v-if="!gameStarted" class="game-intro">
        <p>翻牌找到相同的单词对，考验你的记忆力！</p>
        <div class="game-controls">
          <button class="btn" @click="startGame">开始游戏</button>
        </div>
      </div>
      
      <div v-else-if="gameEnded" class="game-result">
        <h2>游戏结束！</h2>
        <div class="score-display">
          <div class="score">用时: {{ formatTime(timeElapsed) }}</div>
          <div class="moves">翻牌次数: {{ moves }}</div>
          <div class="pairs">找到配对: {{ matchedPairs.length / 2 }}/{{ totalPairs }}</div>
        </div>
        <div class="game-controls">
          <button class="btn" @click="restartGame">再玩一次</button>
          <button class="btn" @click="goHome">返回首页</button>
        </div>
      </div>
      
      <div v-else class="game-area">
        <div class="game-info">
          <div class="timer">时间: {{ formatTime(timeElapsed) }}</div>
          <div class="moves">翻牌次数: {{ moves }}</div>
          <div class="pairs">配对: {{ matchedPairs.length / 2 }}/{{ totalPairs }}</div>
        </div>
        
        <div class="memory-grid">
          <div 
            v-for="(card, index) in cards" 
            :key="index"
            class="memory-card"
            :class="{ 
              'flipped': card.isFlipped || card.isMatched,
              'matched': card.isMatched
            }"
            @click="flipCard(index)"
          >
            <div class="card-front">
              <span class="card-text">?</span>
            </div>
            <div class="card-back">
              <span class="card-text">{{ card.content }}</span>
            </div>
          </div>
        </div>
        
        <div class="game-controls">
          <button class="btn" @click="restartGame">重新开始</button>
          <button class="btn" @click="goHome">返回首页</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getRandomWords } from '../data/words.js'

export default {
  name: 'WordMemory',
  data() {
    return {
      gameStarted: false,
      gameEnded: false,
      cards: [],
      flippedCards: [],
      matchedPairs: [],
      moves: 0,
      timeElapsed: 0,
      timer: null,
      totalPairs: 0
    }
  },
  methods: {
    startGame() {
      this.gameStarted = true
      this.gameEnded = false
      this.initializeCards()
      this.moves = 0
      this.timeElapsed = 0
      this.flippedCards = []
      this.matchedPairs = []
      
      this.timer = setInterval(() => {
        this.timeElapsed++
      }, 1000)
    },
    
    initializeCards() {
      const words = getRandomWords(6) // 6个单词，每对2张牌，总共12张
      this.totalPairs = words.length
      
      // 创建卡片数组，每个单词两张牌
      const cardPairs = []
      words.forEach(word => {
        cardPairs.push(
          { content: word.word, type: 'word', pairId: word.word },
          { content: word.meaning, type: 'meaning', pairId: word.word }
        )
      })
      
      // 随机打乱卡片顺序
      this.cards = cardPairs
        .sort(() => Math.random() - 0.5)
        .map((card, index) => ({
          ...card,
          id: index,
          isFlipped: false,
          isMatched: false
        }))
    },
    
    flipCard(index) {
      const card = this.cards[index]
      
      // 如果卡片已经翻过或已匹配，则忽略
      if (card.isFlipped || card.isMatched) return
      
      // 如果已经翻了两张牌，等待动画完成
      if (this.flippedCards.length >= 2) return
      
      // 翻转卡片
      card.isFlipped = true
      this.flippedCards.push(card)
      
      // 如果翻了两张牌，检查是否匹配
      if (this.flippedCards.length === 2) {
        this.moves++
        this.checkMatch()
      }
    },
    
    checkMatch() {
      const [card1, card2] = this.flippedCards
      
      // 检查是否匹配（相同的pairId）
      if (card1.pairId === card2.pairId) {
        // 匹配成功
        card1.isMatched = true
        card2.isMatched = true
        this.matchedPairs.push(card1.id, card2.id)
        
        // 检查游戏是否结束
        if (this.matchedPairs.length === this.totalPairs * 2) {
          setTimeout(() => {
            this.endGame()
          }, 500)
        }
      } else {
        // 匹配失败，延迟后翻回
        setTimeout(() => {
          card1.isFlipped = false
          card2.isFlipped = false
        }, 1000)
      }
      
      // 清空翻牌数组
      setTimeout(() => {
        this.flippedCards = []
      }, 1000)
    },
    
    endGame() {
      clearInterval(this.timer)
      this.gameEnded = true
    },
    
    restartGame() {
      this.gameStarted = false
      this.gameEnded = false
    },
    
    goHome() {
      this.$router.push('/')
    },
    
    formatTime(seconds) {
      const mins = Math.floor(seconds / 60)
      const secs = seconds % 60
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    }
  },
  
  beforeUnmount() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style scoped>
h1 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 20px;
}

.game-intro p {
  text-align: center;
  color: #7f8c8d;
  font-size: 1.2em;
  margin-bottom: 30px;
}

.game-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 10px;
}

.game-info > div {
  background: linear-gradient(45deg, #74b9ff, #0984e3);
  color: white;
  padding: 10px 20px;
  border-radius: 20px;
  font-weight: bold;
  flex: 1;
  min-width: 100px;
  text-align: center;
}

.memory-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
  margin-bottom: 30px;
  max-width: 600px;
  margin-left: auto;
  margin-right: auto;
}

.memory-card {
  aspect-ratio: 1;
  perspective: 1000px;
  cursor: pointer;
  touch-action: manipulation;
  -webkit-tap-highlight-color: transparent;
  user-select: none;
}

.memory-card .card-front,
.memory-card .card-back {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  border-radius: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 1.2em;
  transition: transform 0.6s;
  box-shadow: 0 8px 25px rgba(0,0,0,0.1);
}

.memory-card .card-front {
  background: linear-gradient(135deg, #74b9ff, #0984e3);
  color: white;
  transform: rotateY(0deg);
}

.memory-card .card-back {
  background: linear-gradient(135deg, #a29bfe, #6c5ce7);
  color: white;
  transform: rotateY(180deg);
}

.memory-card.flipped .card-front {
  transform: rotateY(180deg);
}

.memory-card.flipped .card-back {
  transform: rotateY(0deg);
}

.memory-card.matched .card-back {
  background: linear-gradient(135deg, #00b894, #00cec9);
}

.memory-card:hover {
  transform: scale(1.05);
}

.memory-card.matched:hover {
  transform: none;
}

.card-text {
  text-align: center;
  word-break: break-word;
  padding: 10px;
  line-height: 1.2;
}

.game-controls {
  text-align: center;
  margin-top: 20px;
}

.game-controls .btn {
  margin: 0 10px;
  margin-bottom: 10px;
}

.game-result {
  text-align: center;
}

.game-result h2 {
  color: #2c3e50;
  margin-bottom: 30px;
  font-size: 2em;
}

.score-display {
  margin-bottom: 30px;
}

.score-display > div {
  margin: 10px 0;
  font-size: 1.2em;
  font-weight: bold;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .memory-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
    max-width: 100%;
  }
  
  .game-info {
    flex-direction: column;
    align-items: center;
  }
  
  .game-info > div {
    min-width: auto;
    font-size: 14px;
    padding: 8px 15px;
  }
  
  .card-text {
    font-size: 1em;
  }
  
  .game-controls .btn {
    display: block;
    width: 100%;
    margin: 5px 0;
  }
  
  h1 {
    font-size: 1.8em;
  }
  
  .game-intro p {
    font-size: 1em;
  }
}

@media (max-width: 480px) {
  .container {
    padding: 5px;
  }
  
  .memory-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }
  
  .card-text {
    font-size: 0.9em;
    padding: 5px;
  }
  
  .game-info > div {
    font-size: 12px;
    padding: 6px 12px;
  }
  
  .memory-card .card-front,
  .memory-card .card-back {
    font-size: 1em;
  }
}

/* 横屏优化 */
@media (max-height: 500px) and (orientation: landscape) {
  .memory-grid {
    grid-template-columns: repeat(6, 1fr);
    gap: 8px;
  }
  
  .card-text {
    font-size: 0.8em;
    padding: 3px;
  }
}

/* 触摸设备优化 */
@media (hover: none) and (pointer: coarse) {
  .memory-card:hover {
    transform: none;
  }
  
  .memory-card:active {
    transform: scale(0.95);
  }
  
  .memory-card.flipped:active {
    transform: scale(1.02);
  }
}
</style> 